package com.project.shiro;


import com.project.result.Result;
import com.project.result.ResultCode;
import com.project.service.IUserService;
import com.project.util.WebUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 重写accessAllowed方法
 * 作用是需要进行权限验证的请求进入过滤器后，先判断token的有效性。
 * 在判断是否拥有该权限。
 */
public class RestAuthorizationFilter  extends PermissionsAuthorizationFilter {
    @Resource
    private IUserService userInfoService;

    //如果返回false，则会调用onAccessDenied方法
    @Override
    protected boolean pathsMatch(String path, ServletRequest request) {
        //获取请求的路径
        String requestURI = this.getPathWithinApplication(request);
        System.out.println("东方闪电"+requestURI);
        String[] strings = path.split("==");
        if (strings.length <= 1) {
            // 普通的 URL, 正常处理
            return this.pathsMatch(strings[0], requestURI);
        } else {
            // 获取当前请求的 http method.
            String httpMethod = WebUtils.toHttp(request).getMethod().toUpperCase();
            // 匹配当前请求的 http method 与 过滤器链中的的是否一致
            return httpMethod.equals(strings[1].toUpperCase()) && this.pathsMatch(strings[0], requestURI);
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        // 如果未登录
        if(subject.getPrincipal() == null){
            WebUtil.writeValueAsString(response, Result.fail(ResultCode.USER_AUTHENTICATION_ERROR));
        } else {
            WebUtil.writeValueAsString(response, Result.fail(ResultCode.USER_AUTHORIZATION_ERROR));
        }
        return false;
    }


}
